package models

import (
	"errors"
	"log"
	"rongyy/src/app"
)

type OrderInfoItem struct {
	CarPlateNumber    string `json:"car_plate_number"`
	CarOwnerName      string `json:"car_owner_name"`
	CarOwnerIdNo      string `json:"car_owner_id_no"`
	CarOwnerCellphone string `json:"car_owner_cellphone"`
	LicensePic        string `json:"license_pic"`
	IdFrontPic        string `json:"id_front_pic"`
	IdBackPic         string `json:"id_back_pic"`
}

type OrdersModel struct {
	BaseModel   `xorm:"extends"`
	UserId      int64         `json:"user_id"`
	OrderSn     string        `json:"order_sn"`
	ProductName string        `json:"product_name"`
	Price       float64       `json:"price"`
	Amount      int           `json:"amount"`
	Status      string        `json:"status"`
	PayStatus   string        `json:"pay_status"`
	MerchantId  int64         `json:"merchant_id"`
	Type        string        `json:"type"`
	Remark      string        `json:"remark"`
	OrderInfo   OrderInfoItem `json:"order_info" xorm:"json"`
}

func (rm *OrdersModel) TableName() string {
	return "orders"
}

func (rm *OrdersModel) Create() error {
	_, err := app.DB().Insert(rm)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

func (rm *OrdersModel) UpdateStatus() error {
	if rm.OrderSn == "" {
		return errors.New("订单号缺失")
	}
	_, err := app.DB().Where("order_sn=? ", rm.OrderSn).Cols("status").Update(rm)
	if err != nil {
		return err
	}
	return err
}

func (rm *OrdersModel) FindByStatus(orderSn string, status int) (bool, error) {
	po := &OrdersModel{}
	has, err := app.DB().Where("order_sn=? and order_status=?", orderSn, status).Get(po)
	if err != nil {
		log.Println(err)
		return false, err
	}
	return has, nil
}

func (rm *OrdersModel) FindByOrder(orderSn string) (*OrdersModel, bool, error) {
	po := &OrdersModel{}
	has, err := app.DB().Where("order_sn=?", orderSn).Get(po)
	if err != nil {
		return nil, false, err
	}
	return po, has, nil
}
